package com.yisin.ssh2.csharp;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

import com.yisin.ssh2.jsch.SftpProgressMonitor;

public class Timer extends Thread {

	private long millis = 10;
	private boolean run_flag = false;
	private ElapsedEventHandler elap = null;

	public Timer(long millis) {
		this.millis = millis;
	}
	
	public void run(){
		ElapsedEventArgs args = null;
		while(run_flag){
			try {
				Thread.sleep(millis);
			} catch (InterruptedException e) {
			}
			if(null != elap){
				try {
					args = new ElapsedEventArgs();
					args.setSignalTime(new Date());
					elap.timerElapsed(this, args);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void Start() {
		run_flag = true;
		this.start();
	}

	public void Stop() {
		run_flag = false;
		this.stop();
	}

	public void Dispose() {
		run_flag = false;
		this.destroy();
	}

	public void Elapsed(ElapsedEventHandler elap) {
		this.elap = elap;
	}

	public static class ElapsedEventHandler {
		private SftpProgressMonitor monitor;
		private String methodName;
		
		public ElapsedEventHandler(SftpProgressMonitor monitor, String methodName) {
			this.monitor = monitor;
			this.methodName = methodName;
		}
		
		public void timerElapsed(Object sender, ElapsedEventArgs args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
			Method method = monitor.getClass().getMethod(methodName, new Class[]{Object.class, ElapsedEventArgs.class });
			if(null != method){
				method.invoke(sender, args);
			}
		}

	}

	public static class ElapsedEventArgs {
		public Date SignalTime;

		public Date getSignalTime() {
			return SignalTime;
		}

		public void setSignalTime(Date signalTime) {
			SignalTime = signalTime;
		}
	}

}
